#!/usr/bin/env python
# SPDX-License-Identifier: LGPL-2.1-or-later
#
# Copyright (C) 2015 Analog Devices, Inc.
# Author: Paul Cercueil <paul.cercueil@analog.com>

import sys

if sys.version_info[0] < 3:
    from distutils.core import setup
    from distutils.command.install import install

    config = dict()
else:
    from setuptools import setup
    from setuptools.command.install import install

    config = dict(long_description_content_type="text/markdown")

description = "Library for interfacing with Linux IIO devices"

try:
    with open("${CMAKE_CURRENT_SOURCE_DIR}/README.md", "r") as fh:
        long_description = fh.read()
except:
    long_description = description


def find_recursive(folder, filename):
    import os

    for root, dirs, files in os.walk(folder):
        for file in files:
            if file == filename:
                return os.path.join(root, file)


class InstallWrapper(install):
    """Before installing we check if the
    libiio library is actually installed"""

    def run(self):
        self._check_libiio_installed()
        # Run the standard PyPi copy
        install.run(self)

    def _check_libiio_installed(self):
        cross_compiling = ("${CMAKE_CROSSCOMPILING}" == "TRUE")
        if cross_compiling:
            # When cross-compiling, we generally cannot dlopen
            # the libiio shared lib from the build platform.
            # Simply skip this check in that case.
            return

        from platform import system as _system
        from ctypes import CDLL as _cdll
        from ctypes.util import find_library
        from os import getenv
        from os.path import join

        iiolib = "iio" if "Darwin" in _system() else "libiio${CMAKE_SHARED_LIBRARY_SUFFIX}"

        destdir = getenv("DESTDIR", "") or ""
        destdir = join("${CMAKE_INSTALL_FULL_LIBDIR}", destdir)
        fulllibpath = find_recursive(destdir, iiolib)

        try:

            _lib = _cdll(fulllibpath, use_errno=True, use_last_error=True)
            if not _lib._name:
                raise OSError
        except OSError:
            msg = "The libiio library could not be found.\n\
            libiio needs to be installed first before the python bindings.\n\
            The latest release can be found on GitHub:\n\
            https://github.com/analogdevicesinc/libiio/releases"
            raise Exception(msg)


config.update(
    dict(
        name="pylibiio",
        version="${VERSION}",
        maintainer="Analog Devices, Inc",
        maintainer_email="travis.collins@analog.com",
        description=description,
        long_description=long_description,
        url="https://github.com/analogdevicesinc/libiio",
        py_modules=["iio"],
        cmdclass={"install": InstallWrapper},
        license="LGPL-2.1-or-later",
        classifiers=[
            "Programming Language :: Python :: 3",
            "Operating System :: OS Independent",
        ],
    )
)


setup(**config)
